import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:hellow01/model/musicData.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:hellow01/tools/sqflite/sqflite_bussiness/music_sql_bll.dart';
import 'package:path_provider/path_provider.dart';
import '../../Constants/constants.dart';

class MusicDetailPage  extends  StatefulWidget{
  final MusicData songInfo; 
  MusicDetailPage({this.songInfo});
  @override
  _MusicDetailPage createState() {
    return _MusicDetailPage(songInfo: songInfo);
  }
}

class _MusicDetailPage extends State<MusicDetailPage>{
   AudioPlayer audioPlayer = AudioPlayer();
   MusicSqlBll _sqlDb = new  MusicSqlBll();
   Dio dio = new Dio();
   AudioPlayerState _state;
   MusicData songInfo; //歌曲信息
   double _currentRat = 0;
   String _totalTimeStr = ""; //"3:32"
   Directory _filePath; //"3:32"
   double _currentLoadingProgress = 0; //下载进度
   bool _needLoad=false;//一般不展示
   bool _repeaded=false;
   @override
   Widget build(BuildContext context) {
    return Scaffold (
       backgroundColor: Colors.deepOrangeAccent,
       body: SafeArea(child:  Column(
         children:[
           _searchBar(),
           Expanded(child: Swiper(
            itemBuilder: _swiperBuilder,
            itemCount: 3,
            pagination: new SwiperPagination(
                builder: DotSwiperPaginationBuilder(
              color: Colors.black54,
              activeColor: Colors.white,
            )),
            control: new SwiperControl(),
            scrollDirection: Axis.horizontal,
            autoplay: true,
            duration: 900,
            onTap: (index) => print('点击了第$index个'),
           )),
           _playerLayout(),
           _needLoad == true?_loadingLayout():SizedBox(height:0),
           _startAndTermite()
         ]
       ))
    );
  }

  _MusicDetailPage({this.songInfo}){
    audioPlayer.setVolume(1);
     
    audioPlayer.onPlayerError.listen((msg) {
    print('audioPlayer error --------------: $msg');
    setState(() {
      _state = AudioPlayerState.STOPPED;
     // duration = Duration(seconds: 0);
     // position = Duration(seconds: 0);
    });
  });

     //进度变化
     audioPlayer.onDurationChanged.listen((Duration d) {
       //if(songInfo.musicTotalTime == 0|| songInfo.musicTotalTime == null)
      setState((){
        songInfo.musicTotalTime = d.inSeconds;
        int fenzhong = (songInfo.musicTotalTime/60).toInt();
        int miao = songInfo.musicTotalTime - fenzhong * 60;
        _totalTimeStr = fenzhong.toString() + ':' + miao.toString();
        });
    });
    
    //音乐总时长
    audioPlayer.onAudioPositionChanged.listen((Duration  p) {
      setState((){
         var currentPos = p.inSeconds;
         if(songInfo.musicTotalTime!=0)
          _currentRat = currentPos/songInfo.musicTotalTime;
       });
    });

    audioPlayer.onPlayerStateChanged.listen((AudioPlayerState s) async {
       var dsg1 =  (await  getExternalStorageDirectory()).path + '/musicfiles';
       _state = s;
       if(_state == AudioPlayerState.COMPLETED)
       {
          if(_repeaded==true){
             print('--------------');
            audioPlayer.resume();
          }else{
            var path = dsg1 + '/' + songInfo.musicName + "_" + songInfo.singer  + songInfo.nameExtension;
            print(path);
            await audioPlayer.play(path, isLocal: true);
            _repeaded = true;
          }
          //audioPlayer.resume();
       }
    });    

    //播放音乐
    //play();
    //判断本地是否有，若有，则直接播放
    //若无，则下载（下载过程中退出，则删除文件）
    functionFirst();
  }
  
  functionFirst()async{
     var dsg1 =  (await  getExternalStorageDirectory()).path + '/musicfiles';
     _filePath = Directory(dsg1);
     bool hasExisted = await _filePath.exists();
     //不存在就边下边播
     if (!hasExisted) {
       playAndLoad();
     }
     else{
       //看是否有文件，有则直接播放，否则边下边播
       List<FileSystemEntity> files = _filePath.listSync();
       bool has = false;
       for(var inter in files){
          if(inter.path.contains(songInfo.musicName)){
            has = true;
            //直接播放，需注意的是(不可能是破损文件，因为若在下载时退出，则删除正在下的文件)
            playLocal(inter.path);
            return;
          }
       }
       if(has == false){
          playAndLoad();
       }
     }
    //是否隐藏下载条
    setState(() {
           _needLoad = true;
    });
  }

  playAndLoad()async{
      //在线播放
      playOnLine();
      //下载
      loadFile();
  }
  
  playLocal(String path)async{
     await audioPlayer.play(path, isLocal: true);
  }
  
  //在线播放
  playOnLine() async {
     var songInfoStr = songInfo.musicName + '_' + songInfo.singer + songInfo.nameExtension;
     var url ='http://139.196.170.157/audio/$songInfoStr';
     int result = await audioPlayer.play(url);
     if (result == 1) {
      
     }
  }

  //下载
  loadFile()async{
    Response response = await dio.download(
          'http://139.196.170.157/audio/'+songInfo.musicName + '_' + songInfo.singer + songInfo.nameExtension, _filePath.path+'/'+ songInfo.musicName + '_' + songInfo.singer+ songInfo.nameExtension, onReceiveProgress: (received, total) {
        if (total != -1) {
          ///当前下载的百分比例
          print((received / total * 100).toStringAsFixed(0) + "%");
          setState(() {
              _currentLoadingProgress = received / total;
          });
          if(_currentLoadingProgress == 1){
              insertDatabase();
          }          
        }
      });
  }

  //插入数据到数据库
  insertDatabase(){
      var songInfoEntity = new MusicData(songInfo.musicName,songInfo.singer,1,'music',songInfo.nameExtension);
      _sqlDb.addSongInfo(songInfoEntity);
  }

  //搜索框
  Row _searchBar(){
    return Row(children: [
      Container(
        width: Constants.Wh * 130,
        height: Constants.Wh * 140,
        child: FlatButton(
                    onPressed: ()=> { Navigator.pop(context) },
                    padding: EdgeInsets.all(0),
                    child: Image.asset(
                      'assets/images/ima_left_arrow.png',
                      width: Constants.Wh * 18,
                      height: Constants.Hh * 46,
                      fit: BoxFit.fill,
                    )),),
       //Expanded(child: Text(songInfo.musicName),),
       Row(children: [Text(songInfo.musicName,style: TextStyle(
              fontSize: 18,
              color: Colors.black,
            ),),SizedBox(width:10),Text(songInfo.singer,style: TextStyle(
              fontSize: 16,
              color: Colors.black54,
            ),)],)
    ],);
  }

  Row _playerLayout(){
     return Row(children: [
       Expanded(
       child:  LinearProgressIndicator(
       backgroundColor: Colors.blue,
       value: _currentRat,
       valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),
     ),),
     Text(_totalTimeStr)
     ],);
  }

  //下载进度条
  Row _loadingLayout(){
     return Row(children: [
       Expanded(
       child:  LinearProgressIndicator(
       backgroundColor: Colors.grey,
       value: _currentLoadingProgress,
       valueColor: new AlwaysStoppedAnimation<Color>(Colors.lime),
     ),),
     //Text(_totalTimeStr)
     ],);
  }

  //开始和暂停
  RaisedButton _startAndTermite(){
    return RaisedButton(child:Text('开始和暂停'),onPressed: (){
     if(_state == AudioPlayerState.PLAYING){
       audioPlayer.pause();
     }
     else if(_state == AudioPlayerState.PAUSED){
         audioPlayer.resume();
     }
     else if(_state == AudioPlayerState.COMPLETED){
       audioPlayer.resume();
     }
    },);
  }

  //图片轮播 
  Widget _swiperBuilder(BuildContext context, int index) {
    if(index == 0)
     return (Image.asset(
                      'assets/images/ima_ff1.jpg',
                      fit: BoxFit.fill,
                    ));
                     if(index == 1)
     return (Image.asset(
                      'assets/images/ima_ff.jpg',
                      fit: BoxFit.fill,
                    ));
                     if(index == 2)
     return (Image.asset(
                      'assets/images/ima_ff2.jpg',
                      fit: BoxFit.fill,
                    ));
  }

  @override
  void dispose()async{
    await audioPlayer.release();
    //如果正在下载，则删除文件
    if(_currentLoadingProgress >0 && _currentLoadingProgress<1){
       var sdg = 1;
      List<FileSystemEntity> files = _filePath.listSync();
      var sddg = files.firstWhere((element) => element.path.contains(songInfo.musicName));
      //删除文件
      sddg.delete();
    }
    super.dispose();
  }
}